package com.example.lenovo.shixi;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class picture extends AppCompatActivity {
    private ImageView imageView;
    private Button camera;
    private Button upload;
    private Button photo;
    private TextView textView;
    private String img;
    private File mPhotoFile;
    private String mPhotoPath;
    private Intent intent;
    private String mpath = "http://42.159.6.14:5555/getImage";

    public final static int CAMERA_RESULT = 0;
    public final static int LOAD_IMAGE = 1;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture);
        Intent i=getIntent();
        imageView = (ImageView) findViewById(R.id.imageView);
        camera = (Button) findViewById(R.id.mcamera);
        photo = (Button) findViewById(R.id.mphoto);
        upload = (Button) findViewById(R.id.mupload);
        textView = findViewById(R.id.text);
        intent = new Intent();
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //点击事件，而重定向到图片库
                Intent it = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()方法
                startActivityForResult(it, LOAD_IMAGE);
            }
        });

        camera.setOnClickListener(new ButtonOnClickListener());

        intent.putExtra("imagePath",mPhotoPath);

        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NetTask nt = new NetTask();
                nt.execute(mpath);
//                intent.setClass(MainActivity.this,IdentifyActivity.class);
//                startActivity(intent);
            }
        });
    }
    class NetTask extends AsyncTask<String, Void, String > {

        @Override
        protected String doInBackground(String... strings) {
            String path = strings[0];
            try {
                JSONObject object = new JSONObject();
                object.put("image", img);

                byte[] data = (object.toString()).getBytes();
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty("Content-Length", data.length + "");
                conn.setRequestProperty("contentType", "application/json");
                conn.setDoOutput(true);
                conn.setUseCaches(false);

                conn.connect();
                OutputStream os = conn.getOutputStream();
                os.write(data);
                os.flush();
                os.close();
                String str="";
                if(conn.getResponseCode()==200){

                    InputStream is=conn.getInputStream();
                    byte [] d = new byte[conn.getContentLength()];
                    is.read(d);
                    str = new String(d);
                }
                return str;
            } catch (Exception e) {
                return null;
            }
        }
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(result == "抱歉，没有帮助到您"){
                Toast.makeText(getApplicationContext(), "(^_^)" + result, Toast.LENGTH_SHORT).show();
            }else{
                textView.setText(result);
            }
        }
    }



    private class ButtonOnClickListener implements View.OnClickListener {
        public void onClick(View v) {
            try {
                if (ContextCompat.checkSelfPermission(picture.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                {
                    ActivityCompat.requestPermissions(picture.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);

                } else {
                        Intent intet = new Intent("android.media.action.IMAGE_CAPTURE");//开始拍照
                        //第二个参数是需要申请的权限
                        mPhotoPath = getSDPath() + "/" + getPhotoFileName();//设置图片文件路径，getSDPath()和getPhotoFileName()具体实现在下面

                        mPhotoFile = new File(mPhotoPath);
                        if (!mPhotoFile.exists()) {
                            mPhotoFile.createNewFile();//创建新文件
                        }
                        intet.putExtra(MediaStore.EXTRA_OUTPUT,//Intent有了图片的信息
                                Uri.fromFile(mPhotoFile));
                        startActivityForResult(intet, CAMERA_RESULT);//跳转界面传回拍照所得数据
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if   (sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();

    }


    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date)  +".jpg";
    }

    /**
     * 用onActivityResult()接收传回的图像，当用户拍完照片，或者取消后，系统都会调用这个函数
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, intent);
        if(requestCode==CAMERA_RESULT){

            if(resultCode==-1){
                Bitmap bitmap = BitmapFactory.decodeFile(mPhotoPath, null);
                imageView.setImageBitmap(bitmap);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                byte bytes[] = os.toByteArray();
                img = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
            }
        }
        if(requestCode==LOAD_IMAGE){
            if(requestCode==1){
                Uri selectedImage = intent.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                //查询我们需要的数据
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                mPhotoPath = cursor.getString(columnIndex);
                cursor.close();
                Bitmap bitmap = BitmapFactory.decodeFile(mPhotoPath, null);
                imageView.setImageBitmap(bitmap);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                byte bytes[] = os.toByteArray();
                img = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
            }
        }
    }
}
